package com.huynhchihieu.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.huynhchihieu.domain.Book;

@Repository
public class BookDAOImpl implements BookDAO {

	@PersistenceContext(name = "persistenceUnit")
	EntityManager entityManager;

	public Book findById(int id) {
		Book books = (Book) entityManager.createNativeQuery("select *from books where book_id = ?", Book.class)
				.setParameter(1, id).getResultList().get(0);
		return books;
	}

	public List<Book> getAll() {
		// TODO Auto-generated method stub
		return null;
	}

	public void upDate(Book book) {
		entityManager.merge(book);
	}

	public List<Book> getAllBooks() {
		return entityManager.createNativeQuery("select * from books", Book.class).getResultList();
	}

	public Book addBook(Book book) {
		return entityManager.merge(book);
	}

	public void updateBook(Book book) {
		entityManager.merge(book);

	}

	public Book finByName(String bookName) {
		List<Book> books = entityManager.createNativeQuery("select * from books where book_name=?", Book.class)
				.setParameter(1, bookName).getResultList();
		if (!books.isEmpty()) {
			return books.get(0);
		}
		return null;
	}

	public void delete(Book book) {
		entityManager.remove(entityManager.contains(book) ? book : entityManager.merge(book));
	}

	public List<Book> finByNames(String bookName) {
		if (!bookName.isEmpty()) {
			return entityManager.createNativeQuery("select * from books where book_name = ?", Book.class)
					.setParameter(1, bookName).getResultList();
		}else{
			return getAllBooks();
		}
	}

}
